package com.qf.util;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.OutputStream;
import java.util.Random;

/**
 * 验证码生成工具类
 * @USER: Administrator
 * @DATE: 2025/8/31 上午9:09
 * @VERSION: 1.0.0
 */
public class CaptchaUtils {
    // 验证码字符集
    private static final String CODE_CHAR = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    // 验证码长度
    private static final int CODE_LENGTH = 4;
    // 图片宽度
    private static final int WIDTH = 120;
    // 图片高度
    private static final int HEIGHT = 40;
    // 干扰线数量
    private static final int LINE_COUNT = 5;
    // 字体大小
    private static final int FONT_SIZE = 20;

    /**
     * 生成验证码图片并返回验证码文本
     * @param os 输出流，用于返回图片
     * @return 生成的验证码文本
     */
    public static String generateCaptcha(OutputStream os) {
        // 创建图片缓冲区
        BufferedImage image = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB);
        Graphics g = image.getGraphics();

        // 设置背景色
        g.setColor(Color.WHITE);
        g.fillRect(0, 0, WIDTH, HEIGHT);

        // 设置边框
        g.setColor(Color.LIGHT_GRAY);
        g.drawRect(0, 0, WIDTH - 1, HEIGHT - 1);

        // 绘制干扰线
        Random random = new Random();
        for (int i = 0; i < LINE_COUNT; i++) {
            g.setColor(new Color(random.nextInt(256), random.nextInt(256), random.nextInt(256)));
            g.drawLine(
                    random.nextInt(WIDTH), random.nextInt(HEIGHT),
                    random.nextInt(WIDTH), random.nextInt(HEIGHT)
            );
        }

        // 绘制验证码字符
        g.setFont(new Font("Arial", Font.BOLD, FONT_SIZE));
        StringBuilder captcha = new StringBuilder();
        for (int i = 0; i < CODE_LENGTH; i++) {
            // 随机获取字符
            char c = CODE_CHAR.charAt(random.nextInt(CODE_CHAR.length()));
            captcha.append(c);
            // 随机颜色和位置
            g.setColor(new Color(random.nextInt(128), random.nextInt(128), random.nextInt(128)));
            g.drawString(String.valueOf(c), 25 * i + 10, 25 + random.nextInt(10));
        }

        // 释放资源
        g.dispose();

        // 输出图片
        try {
            ImageIO.write(image, "JPEG", os);
        } catch (Exception e) {
            throw new RuntimeException("生成验证码失败", e);
        }

        return captcha.toString();
    }
}
